#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 11-May-09 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.IO;
using System.Drawing;
using System.Reflection;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Forms;

using Thn;
using Thn.Text;
using Thn.Interface.Vcl;
#endregion

namespace Thn.Interface.Vcl
{
    /// <summary>
    /// Listbox for showing <see cref="StackTrace"/>.
    /// </summary>    
#if DEBUG
    [ToolboxItem(false)]
    public
#else
    [ToolboxItem(false)]
    public
#endif
 class StackTraceListbox : ListBox
    {
        #region Fields
        int colFile = 0;
        int colLine = 1;
        int colType = 2;
        int colMethod = 3;
        #endregion

        #region Filter System
        private bool mFilterSystem = true;
        /// <summary>
        /// Gets/Sets whether System.* types shall be filtered out.
        /// </summary>
        [Browsable(true), DefaultValue(true), Category("Behavior"), Description("Filter out System.* types")]
        public bool FilterSystem
        {
            get { return mFilterSystem; }
            set { mFilterSystem = value; }
        }
        #endregion

        #region Filter External
        private bool mFilterExternal = true;
        /// <summary>
        /// Gets/Sets whether codes that are not within this assembly shall be filtered out.
        /// </summary>
        [Browsable(true), DefaultValue(true), Category("Behavior"), Description("Filter out external types")]
        public bool FilterExternal
        {
            get { return mFilterExternal; }
            set { mFilterExternal = value; }
        }
        #endregion

        #region Skip Count
        private int mSkipCount = 0;
        /// <summary>
        /// Gets/Sets SkipCount
        /// </summary>
        [Browsable(true), DefaultValue(0), Category("Behavior"), Description("Filter out a certain number of frames.")]
        public int SkipCount
        {
            get { return mSkipCount; }
            set { mSkipCount = value; }
        }
        #endregion

        #region Populate Column
        void PopulateColumns()
        {
            if (Columns.Count == 0)
            {
                Columns.Add("File", 100);

                Columns.Add("Line", 80);
                Columns[colLine].Alignment = ContentAlignment.MiddleCenter;

                Columns.Add("Type", 150);

                Columns.Add("Method", 150);
            }
        }
        #endregion

        #region Bind Data
        /// <summary>
        /// Update the UI contents.
        /// </summary>
        public void Bind(StackTrace stack)
        {
            if (stack == null)
            {
                Items.Clear();
            }
            else
            {
                int count = stack.FrameCount;
                StackFrame frame = null;
                ListBoxItem item;
                Items.Clear();

                int skipCounter = 1;

                for (int i = 0; i < count; i++)
                {
                    if (skipCounter > mSkipCount)
                    {
                        frame = stack.GetFrame(i);
                        if (!FilterFrame(frame))
                        {
                            item = new ListBoxItem();
                            item.Value = frame;
                            Items.Add(item);
                        }
                        #region Defensive tracing
                        else
                        {
                            //frame is filtered out.
                        }
                        #endregion
                    }
                    else skipCounter++;
                }
            }

            DisplayData();

            Invalidate();
        }
        #endregion

        #region Filter Frame
        /// <summary>
        /// Filter out unwanted frames.
        /// </summary>
        bool FilterFrame(StackFrame frame)
        {
            bool result = false;

            if (mFilterExternal)
            {
                string file = frame.GetFileName();
                if ((file == null) || (file == string.Empty))
                {
                    result = true;
                }
            }
            #region Defensive tracing
            else
            {
                //external filtering is not enabled, proceed
            }
            #endregion

            if ((!result) && (mFilterSystem))
            {
                MethodBase method = frame.GetMethod();
                if (method != null)
                {
                    Type type = method.DeclaringType;
                    if (type != null)
                    {
                        if (type.Namespace.Contains("System."))
                        {
                            result = true;
                        }
                        #region Defensive tracing
                        else
                        {
                            //not System.* -> don't filter
                        }
                        #endregion
                    }
                    #region Defensive tracing
                    else
                    {
                        //can't get declaring type -> don't filter
                    }
                    #endregion
                }
                #region Defensive tracing
                else
                {
                    //method is null -> don't filter
                }
                #endregion
            }
            #region Defensive tracing
            else
            {
                //System.* filtering is not enabled, proceed
            }
            #endregion

            return result;
        }
        #endregion

        #region Display Data
        void DisplayData()
        {
            ListBoxItem item = null;
            StackFrame frame = null;
            string file = "";
            MethodBase method = null;
            Type type = null;
            for (int i = 0; i < Items.Count; i++)
            {
                item = Items[i];
                frame = item.Value as StackFrame;
                if (frame != null)
                {
                    method = frame.GetMethod();
                    type = method != null ? method.DeclaringType : null;
                    file = frame.GetFileName();
                    file = Path.GetFileName(file);

                    item[colLine] = string.Format("{0:#,##}", frame.GetFileLineNumber());
                    item[colFile] = file;
                    item[colMethod] = method != null ? method.Name : "";
                    item[colType] = type != null ? type.FullName : "";
                }
            }
        }
        #endregion

        #region Initialize
        void Initialize()
        {
            if (!DesignMode)
            {
                PopulateColumns();
            }
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor
        /// </summary>
        public StackTraceListbox()
        {
            AutoSizedColumn = colMethod;
            DrawTitle = true;
            Initialize();
        }
        #endregion
    }
}
